const express = require('express')
const router = express.Router()
const logger = require('../utils/log4js')
const loginRoute = require('./login')
const convRoute = require('./conv')
const contactRoute = require('./contact')
const userRoute = require('./user')
const { verifyToken } = require('../utils/jwt')

// 白名单
const WHITE_API = ['/login', '/register', '/verifyCode', '/replacePwd', '/upload']

router.use(function (req, res, next) {
    logger.info(`[${req.method}-${req.url}]`, req.body)
    if (!WHITE_API.includes(req.url)) {
        let token = req.headers.token
        try {
            verifyToken(token)
        } catch (e) {
            res.status(401)
            return res.json({
                code: 401
            })
        }
    }
    next()
})

router.post('/login', loginRoute)

router.post('/convList', convRoute.convList)
router.post('/convNews', convRoute.convNews)
router.post('/createConv', convRoute.createConv)
router.post('/sendMsg', convRoute.sendMsg)

router.post('/contactList', contactRoute.contactList)
router.post('/findNoFriendUsers', contactRoute.findNoFriendUsers)
router.post('/appendFriend', contactRoute.appendFriend)
router.post('/appendFriendList', contactRoute.appendFriendList)
router.post('/confirmAppend', contactRoute.confirmAppend)
router.post('/delFriend', contactRoute.delFriend)

router.post('/upload', userRoute.upload)

module.exports = router